package com.business.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.business.dao.ActivitiesLoanMapper;
import com.business.dao.LoanInterestMapper;
import com.business.dao.LoanMapper;
import com.business.domain.*;
import com.business.domain.LoanExample.Criteria;
import com.business.service.LoanService;
import com.sys.Utils.ExcelUtil;
import com.sys.Utils.FileUtils;
import com.sys.result.PageParam;
import com.sys.result.RequestPageVo;
import com.sys.result.RequestResultVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


@Service
public class LoanServiceImpl implements LoanService {

    @Resource
    private LoanMapper loanMapper;

    @Resource
    private ActivitiesLoanMapper activitiesLoanMapper;

    @Resource
    private LoanInterestMapper loanInterestMapper;

    @Override
    public RequestPageVo<Loan> queryLoanList(PageParam param, String productName) {
        RequestPageVo<Loan> pageVo = new RequestPageVo<Loan>();
        LoanExample example = new LoanExample();
        Criteria criteria = example.createCriteria();

        criteria.andIsDeleteEqualTo(false);// 未删除
        example.setOrderByClause("creatime desc");
        if (!StringUtils.isEmpty(productName)) {// 根据productName 产品名称查询
            criteria.andProductNameLike("%" + productName + "%");
        }

        int count = loanMapper.countByExample(example);
        if (count > 0) {
            example.setPageSize(param.getLimit());
            example.setStartPage(param.getOffset());
            List<Loan> loanList = loanMapper.selectByExample(example);
            for (Loan loan : loanList) {
                LoanInterestExample interestexample = new LoanInterestExample();
                example.setOrderByClause("installment");
                com.business.domain.LoanInterestExample.Criteria create = interestexample.createCriteria();
                create.andLoanIdEqualTo(loan.getId());
                List<LoanInterest> list = loanInterestMapper.selectByExample(interestexample);
                loan.setInterestList(list);
            }

            pageVo.setLimit(param.getLimit());
            pageVo.setTotal(count);
            pageVo.setOffset(param.getOffset());
            pageVo.setRows(loanList);

        }

        return pageVo;
    }

    @Override
    public RequestResultVo<Loan> updateLoan(Loan loan, MultipartFile contractFile) {
        RequestResultVo<Loan> result = new RequestResultVo<Loan>();
        try {
            if (contractFile != null) {
                String imgUrl = FileUtils.uploadImg(contractFile);
                if (imgUrl == null) {
                    result.setSuccess(false);
                    result.setErrorMessage("请上传正确格式的图片");
                } else {
                    loan.setImageUrl(imgUrl);
                    loan.setUpdatetime(new Date());
                    loan.setAmountScale(100 - loan.getPayment());
                    loanMapper.updateByPrimaryKeySelective(loan);
                    result.setSuccess(true);
                }
            } else {
                loan.setUpdatetime(new Date());
                loan.setAmountScale(100 - loan.getPayment());
                loanMapper.updateByPrimaryKeySelective(loan);
                result.setSuccess(true);
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorMessage("更新失败!");
        }
        return result;
    }

    @Override
    public RequestResultVo<Loan> addLoan(Loan loan, MultipartFile contractFile) {
        RequestResultVo<Loan> result = new RequestResultVo<Loan>();
        try {
            if (contractFile != null) {
                String imgUrl = FileUtils.uploadImg(contractFile);
                if (imgUrl == null) {
                    result.setSuccess(false);
                    result.setErrorMessage("请上传正确格式的图片");
                } else {
                    loan.setImageUrl(imgUrl);
                    loan.setCreatime(new Date());
                    loan.setAmountScale(100 - loan.getPayment());
                    loanMapper.insertSelective(loan);
                    result.setSuccess(true);
                }
            } else {
                loan.setCreatime(new Date());
                loan.setAmountScale(100 - loan.getPayment());
                loanMapper.insertSelective(loan);
                result.setSuccess(true);
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorMessage("添加失败!");
        }
        return result;
    }

    @Override
    public RequestResultVo<Loan> deleteLoan(Integer id) {
        RequestResultVo<Loan> result = new RequestResultVo<Loan>();
        try {
            Loan loan = loanMapper.selectByPrimaryKey(id);
            loan.setIsDelete(true);
            ActivitiesLoanExample example = new ActivitiesLoanExample();
            com.business.domain.ActivitiesLoanExample.Criteria createCriteria = example.createCriteria();
            createCriteria.andLoanIdEqualTo(id);
            activitiesLoanMapper.deleteByExample(example);
            loanMapper.updateByPrimaryKeySelective(loan);
            result.setSuccess(true);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorMessage("删除失败!");
        }
        return result;
    }

    @Override
    public RequestResultVo<Loan> queryLoanById(Integer id) {
        RequestResultVo<Loan> result = new RequestResultVo<Loan>();
        try {
            Loan loan = loanMapper.selectByPrimaryKey(id);

            result.setResult(loan);
            result.setSuccess(true);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorMessage("查询失败!");
        }
        return result;
    }

    @Override
    public RequestPageVo<LoanInterest> getInterest(Integer id) {
        RequestPageVo<LoanInterest> vo = new RequestPageVo<LoanInterest>();
        LoanInterestExample example = new LoanInterestExample();
        example.setOrderByClause("installment");
        com.business.domain.LoanInterestExample.Criteria createCriteria = example.createCriteria();
        createCriteria.andLoanIdEqualTo(id);

        List<LoanInterest> list = loanInterestMapper.selectByExample(example);
        vo.setRows(list);
        return vo;
    }

    @Override
    @Transactional
    public RequestResultVo<LoanInterest> saveOrUpdateInterest(String json, Integer loanId) {
        RequestResultVo<LoanInterest> result = new RequestResultVo<LoanInterest>();
        JSONArray parseArray = JSONArray.parseArray(json);
        LoanInterestExample example = new LoanInterestExample();
        com.business.domain.LoanInterestExample.Criteria createCriteria = example.createCriteria();
        createCriteria.andLoanIdEqualTo(loanId);
        loanInterestMapper.deleteByExample(example);
        for (Object object : parseArray) {
            LoanInterest loan = new LoanInterest();
            JSONObject o = (JSONObject) object;
            Integer installment = o.getInteger("installment");
            Double interest = o.getDouble("interest");
            loan.setLoanId(loanId);
            // 先删除原有的
            loan.setInstallment(installment);
            loan.setInterest(interest);
            loanInterestMapper.insertSelective(loan);
        }
        return result;
    }

    @Override
    public List<Loan> queryAllLoan() {
        LoanExample example = new LoanExample();
        Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(false);
        return loanMapper.selectByExample(example);
    }

    @Override
    public HSSFWorkbook exportLoan() {

        List<LoanVo> list = loanMapper.getAllLoan();
        String[] heads = {"贷款产品名称", "待款周期", "利率", "首付比例", "最高贷款额度", "最高贷款比例", "限定品牌",
                "贷款最低资历", "收入最高资历", "收入最低要求", "信誉要求", "办理场所", "办理流程", "办理周期",
                "提前还款方式", "产品描述", "企业名称", "企业地址", "法定代表人"};
        HSSFWorkbook hssfWorkbook = null;
        try {
            hssfWorkbook = ExcelUtil.outPutExce("车贷数据", heads, list, LoanVo.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hssfWorkbook;
    }

}
